package com.xueyi.workflow.convert;

import com.github.pagehelper.Page;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页转换工具类
 * 用于简化分页转换器的实现
 *
 * @author xueyi
 */
public class PageConverterUtil {

    /**
     * 将PO分页对象转换为DTO分页对象
     *
     * @param poList PO集合
     * @param mapper 转换函数
     * @param <P> PO类型
     * @param <D> DTO类型
     * @return DTO分页对象
     */
    public static <P, D> Page<D> mapperPageDto(Collection<P> poList, Function<P, D> mapper) {
        if (poList == null) return null;
        if (poList instanceof Page<P> pagePoList) {
            Page<D> pageDtoList = new Page<>();
            copyPageInfo(pagePoList, pageDtoList);
            
            List<D> dtoList = poList.stream()
                .map(mapper)
                .collect(Collectors.toList());
            pageDtoList.addAll(dtoList);
            
            return pageDtoList;
        }
        return null;
    }

    /**
     * 将DTO分页对象转换为PO分页对象
     *
     * @param dtoList DTO集合
     * @param mapper 转换函数
     * @param <D> DTO类型
     * @param <P> PO类型
     * @return PO分页对象
     */
    public static <D, P> Page<P> mapperPagePo(Collection<D> dtoList, Function<D, P> mapper) {
        if (dtoList == null) return null;
        if (dtoList instanceof Page<D> pageDtoList) {
            Page<P> pagePoList = new Page<>();
            copyPageInfo(pageDtoList, pagePoList);
            
            List<P> poList = dtoList.stream()
                .map(mapper)
                .collect(Collectors.toList());
            pagePoList.addAll(poList);
            
            return pagePoList;
        }
        return null;
    }

    /**
     * 复制分页信息
     *
     * @param source 源分页对象
     * @param target 目标分页对象
     * @param <S> 源类型
     * @param <T> 目标类型
     */
    private static <S, T> void copyPageInfo(Page<S> source, Page<T> target) {
        target.setPageNum(source.getPageNum());
        target.setPageSize(source.getPageSize());
        target.setTotal(source.getTotal());
        target.setPages(source.getPages());
        target.setCount(source.isCount());
        target.setReasonable(source.getReasonable());
        target.setPageSizeZero(source.getPageSizeZero());
        target.setCountColumn(source.getCountColumn());
        target.setOrderBy(source.getOrderBy());
        target.setOrderByOnly(source.isOrderByOnly());
    }
}
